function S = fillMatrix(M, M_name, R, U, C, PI)

%Fill the connection matrix M with 1's using the rules from R and uniques id
%from U. Using U it will go trhough the R struct to see if there are
%matching subjects and then find the objs corrosponding to it. It will then
%fill M in the corrosponding location
% M = Square Marix with size corrosponding to all possible connections
% M_name = Row & Col names corrosponding to the R_mat
% R = Struct containing all the rules for the project
% U = unique subject ids
% C = collection ids
% PI = project_id
%
%Romesh Stanislaus May 2009


%fill the matrix by layers
%1st Layer: PI & collections
loc_pi = strmatch(num2str(PI),M_name,'exact'); %loc of pi in the matrix
for t = 1:size(C,1)
    for d = 1:size(M_name,1)
        if strcmp(C{t,1},M_name{d,1})
            %found a match link the two
            M(loc_pi, d) = 1; %put 1 to link the 2
        end
    end
end
%2nd layer: relationship btw Collections using Rules
for t = 1:size(U,1)
    for d = 1:size(R,1)
        if strcmp(R(d).subject, U{t,1})
            %found a SUBJECT match
            for iai = 1:size(C,1)
                if strcmp(R(d).object, C{iai,1})
                    %found a OBJECT match
                    loc_sub = strmatch(R(d).subject, M_name, 'exact'); 
                    loc_obj = strmatch(R(d).object, M_name, 'exact');
                    M(loc_sub, loc_obj) = 1; %put 1 to link the 2
                end
            end
        end
    end
end
%3rd layer: relationaship btw rules and items...
for k = 1:size(R,1)
    %get the location of subject and object in the M_name matrix
    loc_sub = strmatch(R(k).subject, M_name, 'exact');
    loc_obj = strmatch(R(k).object, M_name, 'exact');
    M(loc_sub, loc_obj) = 1; %put 1 to link the 2
end

%clear diagonal of 1's if any inserted
for t = 1:size(M,1)
    M(t,t) = 0;
end

S.matrix=M;
S.M_name=M_name;
